﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace Athena.Runtime.Server.Implementations
{
    using ExceptionHandler;
    using Message;
    public class ServiceEntrySelector : IServiceEntrySelector
    {
        private readonly Dictionary<string, ServiceEntry> _serviceEntryDictionary;

        public ServiceEntrySelector(IEnumerable<Type> sourceTypes, IServiceDiscover serviceDiscover)
        {
            _serviceEntryDictionary = new Dictionary<string, ServiceEntry>();
            foreach (var serviceEntry in serviceDiscover.GetEntries(sourceTypes))
            {
                _serviceEntryDictionary.Add(serviceEntry.CorrelationId, serviceEntry);
            }
        }

        public ServiceEntry[] SelectAll()
        {
            return _serviceEntryDictionary.Values.ToArray();
        }

        public ServiceEntry Select(RpcInvokeMessage rpcInvokeMessage)
        {
            //if (!_serviceEntryDictionary.ContainsKey(rpcInvokeMessage.CorrelationId))
            //{
            //    throw new RpcException(AthenaRpcInvokeResultCodeDisplay.RpcServiceEntrySelectException, $"获取ServiceEntry失败,Service：{rpcInvokeMessage.CorrelationId} 不存在。");
            //}

            _serviceEntryDictionary.TryGetValue(rpcInvokeMessage.CorrelationId,out ServiceEntry serviceEntry);
            return serviceEntry;
        }
    }
}
